package com.suirich.servlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import com.suirich.utils.FileUtils;

/**
 * xhEditor文件上传的Java
 *
 * @author ZhangWenLong
 */
@SuppressWarnings("deprecation")
public class UploadImageServlet extends HttpServlet {

    private static final long serialVersionUID = 1541334866883495283L;

    private static Long maxSize = 5242880L;
    
    /**
     * 上传文件数据处理过程 
     */
    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");

        String filePath = request.getParameter("filePath");
        
        String photoPath = request.getSession().getServletContext()
                .getRealPath(filePath)
                + File.separator;
        
        String err = "";
        String newFileName = "";

        if ("application/octet-stream".equals(request.getContentType())) {
            try {
                String dispoString = request.getHeader("Content-Disposition");

                int iFindStart = dispoString.indexOf("name=\"") + 6;

                int iFindEnd = dispoString.indexOf("\"", iFindStart);

                iFindStart = dispoString.indexOf("filename=\"") + 10;

                iFindEnd = dispoString.indexOf("\"", iFindStart);

                String originalFilename = dispoString.substring(iFindStart,
                        iFindEnd);

                String extName = FileUtils.getExtention(originalFilename)
                        .toLowerCase();

                String fileName = new Date().getTime() + extName;

                int i = request.getContentLength();

                byte buffer[] = new byte[i];

                int j = 0;
                while (j < i) { // 获取表单的上传文件
                    int k = request.getInputStream().read(buffer, j, i - j);
                    j += k;
                }

                if (buffer.length == 0) { // 文件是否为空
                    printInfo(response, "上传文件不能为空", "");
                    return;
                }
                if (maxSize > 0 && buffer.length > maxSize) { // 检查文件大小
                    printInfo(response, "上传文件的大小超出限制", "");
                    return;
                }
                
                OutputStream out = new BufferedOutputStream(
                        new FileOutputStream(photoPath + fileName, true));

                out.write(buffer);
                out.close();

                newFileName = "!" + request.getContextPath() + filePath + fileName;

            } catch (Exception ex) {
                newFileName = "";
                err = "错误: " + ex.getMessage();
            }
        } else {
            DiskFileUpload upload = new DiskFileUpload();
            
            try {
                List<FileItem> items = upload.parseRequest(request);

                Map<String, Serializable> fields = new HashMap<String, Serializable>();

                Iterator<FileItem> iter = items.iterator();

                while (iter.hasNext()) {

                    FileItem item = (FileItem) iter.next();

                    if (item.isFormField())
                        fields.put(item.getFieldName(), item.getString());
                    else
                        fields.put(item.getFieldName(), item);
                }

                FileItem uploadFile = (FileItem) fields.get("filedata"); // 获取表单的上传文件
                
                if (uploadFile.getSize() == 0) { // 文件是否为空
                    printInfo(response, "上传文件不能为空", "");
                    return;
                }
                if (maxSize > 0 && uploadFile.getSize() > maxSize) { // 检查文件大小
                    printInfo(response, "上传文件的大小超出限制", "");
                    return;
                }
                
                String originalFilename = uploadFile.getName(); // 获取文件名
                
                String extName = FileUtils.getExtention(originalFilename)
                        .toLowerCase();

                String fileName = new Date().getTime() + extName;

                File savefile = new File(photoPath + fileName);

                uploadFile.write(savefile); // 存储上传文件

                newFileName = "!" + request.getContextPath() + filePath + fileName;

            } catch (Exception ex) {
                newFileName = "";
                err = "错误: " + ex.getMessage();
            }
        }
        printInfo(response, err, newFileName);
    }

    /**
     * 使用I/O流输出 json格式的数据
     * @param response
     * @param err
     * @param newFileName
     * @throws IOException
     */
    protected void printInfo(HttpServletResponse response, String err,
            String newFileName) throws IOException {

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        out.println("{\"err\":\"" + err + "\",\"msg\":\"" + newFileName + "\"}");

        out.flush();
        out.close();

    }

}